package ai.people.netmon.warning.service.impl;

import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.netmon.warning.property.WarningDataSyncNotifyProperties;
import ai.people.netmon.warning.service.WarningDataSyncNotifyService;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiGuanNan
 * @date 2022/8/13 14:53
 */
@Slf4j
@Service
public class WarningDataSyncNotifyServiceImpl implements WarningDataSyncNotifyService {

    @Autowired
    private WarningDataSyncNotifyProperties warningDataSyncNotifyProperties;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通知
     *
     * @param accountId 帐户id
     * @param platform  平台
     */
    @Override
    public void notify(String accountId, String platform) {
        Map<String, String> notifyUrlMap = warningDataSyncNotifyProperties.getUrlMap();
        AssertUtils.isFalse(CollectionUtils.isEmpty(notifyUrlMap), CommonEnum.CONFIGURATION_ERROR);
        String url = notifyUrlMap.get(platform);
        AssertUtils.isFalse(StringUtils.isBlank(url), CommonEnum.CONFIGURATION_ERROR);

        Stopwatch elapsedTime = Stopwatch.createStarted();

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        List<Object> dataList = new ArrayList<>();
        HashMap<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("infoType", platform);
        dataMap.put("crawlInterval", 86400);
        dataMap.put("accountLink","");
        dataMap.put("partnerId", Lists.newArrayList("110000"));
        dataMap.put("account", accountId);
        dataList.add(dataMap);
        JSONObject requestMap = new JSONObject();
        requestMap.put("infoType", platform);
        requestMap.put("data", dataList);

        HttpEntity<JSONObject> entity = new HttpEntity<>(requestMap, headers);

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, entity, JSONObject.class);
        elapsedTime.stop();
        log.info("通知采集任务响应结果：{}, 请求耗时：{}", responseEntity, elapsedTime);
    }
}
